package org.mparts.client;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.mparts.client.mvp.AppPlaceFactory;
import org.mparts.client.mvp.MpartsPlaceHistoryMapper;
import org.mparts.client.place.MainPlace;
import org.mparts.client.ui.IMenuView.IMenuPresenter;
import org.mparts.client.ui.events.LoadUserEvent;
import org.mparts.client.utils.Utils;

import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.activity.shared.ActivityManager;
import com.google.gwt.activity.shared.ActivityMapper;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceController;
import com.google.gwt.place.shared.PlaceHistoryHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
import com.sencha.gxt.widget.core.client.container.Viewport;

public class MpartsApp {

	  @Inject
	  private EventBus eventBus;

	  @Inject
	  private PlaceController placeController;

	  @Inject
	  private ActivityMapper activityMapper;

	  @Inject
	  private MpartsShell shell;
	  
	  @Inject
	  AppPlaceFactory factory;

	  private static final Logger log = Logger.getLogger(MpartsApp.class.getName());
	  
	  public MpartsApp() {
		// TODO Auto-generated constructor stub
	}

	  public void run() {
		    init();
		  }

	private void init() {
    	Log.setUncaughtExceptionHandler();
    	if ( !GWT.isProdMode() ) {
    		Log.setCurrentLogLevel(Log.LOG_LEVEL_DEBUG);
    	} else {
    		Log.setCurrentLogLevel(Log.LOG_LEVEL_OFF);
    	}
//	    GWT.setUncaughtExceptionHandler(new GWT.UncaughtExceptionHandler() {
//	        public void onUncaughtException(Throwable e) {
//	          //Window.alert("Error: " + e.getMessage());
//	        }
//	      });
//		Viewport view = new Viewport();
//		view.add(shell);
//		RootPanel.get("mainArea").add(view);
//		onReady();
    	
	   	 ActivityManager activityManager = new ActivityManager(activityMapper, eventBus);
	   	 activityManager.setDisplay(shell.getDisplay());
		MainPlace defaultPlace = factory.getMainPlace();
	   	 MpartsPlaceHistoryMapper historyMapper = GWT.create(MpartsPlaceHistoryMapper.class);
	   	 historyMapper.setFactory(factory);
	   	 final PlaceHistoryHandler historyHandler = new PlaceHistoryHandler(historyMapper);
	   	 historyHandler.register(placeController, eventBus, defaultPlace);	    
	    
			Log.info("host name: " + Window.Location.getHostName());
			Log.info("current URL: " + Window.Location.getHref());
			Utils.getMpartsService().getUser(Window.Location.getHref(), new AsyncCallback<List<String>>() {

				@Override
				public void onFailure(Throwable caught) {
//					RootPanel.get().add(shell);
					//onReady();
					
//					History.newItem("main:");
//					historyHandler.handleCurrentHistory();
				}

				@Override
				public void onSuccess(List<String> result) {
					if ( result != null && result.size() >= 4 ) {
						String userName = result.get(0);
						String loginUrl = result.get(1);
						Log.info("current user: [" + userName + "], login URL: " + loginUrl + "]");
						Log.info("allow manage: [" + result.get(3) + "], logout URL: " + result.get(2) + "]");
						Utils.setUserData(result);
						eventBus.fireEvent(new LoadUserEvent());
						final Viewport view = new Viewport();
						view.add(shell);
						RootPanel.get(/*"mainArea"*/).add(view);
						Scheduler.get().scheduleDeferred(new ScheduledCommand() {
							
							@Override
							public void execute() {
								historyHandler.handleCurrentHistory();
//								onReady();			
								shell.forceLayout();								
							}
						});
					}
					
				}
			});
		
		
	}

//	@Override
//	public void goTo(Place place) {
//		placeController.goTo(place);
//	}
	
	private native void onReady() /*-{
		if (typeof $wnd.GxtReady != 'undefined') {
			$wnd.GxtReady();
		}
	}-*/;

}
